import plugin from '../../lib/plugins/plugin.js'
import { XiuXianData } from './xiuxian_data.js'
import { XiuXianUtils } from './xiuxian_utils.js'

export class XiuXianRanking extends plugin {
    constructor() {
        super({
            name: '修仙文游排行',
            dsc: '修仙游戏的排行榜功能',
            event: 'message',
            priority: 5000,
            rule: [
                { reg: '^排行榜$', fnc: 'showRanking' },
                { reg: '^(妖怪击杀|灵石|境界修为|宗门|技能|探索|战斗力)排行$', fnc: 'showSpecificRanking' }
            ]
        })
        this.data = new XiuXianData()
        this.utils = new XiuXianUtils()
    }

    async showRanking(e) {
        const rankingTypes = [
            '妖怪击杀排行',
            '灵石排行',
            '境界修为排行',
            '宗门排行',
            '探索排行',
            '战斗力排行'
        ];

        const rankingList = rankingTypes.map(type => `- ${type}`).join('\n');

        const avatarUrl = `![图片 #20px #20px](https://q1.qlogo.cn/g?b=qq&s=0&nk=${e.user_id})`;
        const msg = `${avatarUrl}修仙世界排行榜
    ***
    # 可用的排行榜类型：
    \`\`\`
    ${rankingList}
    \`\`\`
    请输入具体的排行榜类型查看详细排名，如"妖怪击杀排行"`;

        const forwardMsg = await this.utils.markdown(e, msg, '修仙排行榜');
        return this.reply(forwardMsg);
    }

    async showSpecificRanking(e) {
        const rankingType = e.msg.replace('排行', '').trim();
        let ranking;

        switch (rankingType) {
            case '妖怪击杀':
                ranking = this.getMonsterKillRanking();
                break;
            case '灵石':
                ranking = this.getLingshiRanking();
                break;
            case '境界修为':
                ranking = this.getRealmRanking();
                break;
            case '宗门':
                ranking = this.getSectRanking();
                break;
            case '探索':
                ranking = this.getExplorationRanking();
                break;
            case '战斗力':
                ranking = this.getCombatPowerRanking();
                break;
            default:
                return this.reply('未知的排行榜类型');
        }

        const rankingMsg = this.formatRanking(rankingType, ranking);
        const avatarUrl = `![图片 #20px #20px](https://q1.qlogo.cn/g?b=qq&s=0&nk=${e.user_id})`;
        const msg = `${avatarUrl}修仙世界排行榜
***
#${rankingType}排行榜
${rankingMsg}`.trim();

        const forwardMsg = await this.utils.markdown(e, msg, '修仙排行榜');
        return this.reply(forwardMsg);
    }

    getMonsterKillRanking() {
        return Object.entries(this.data.gameState)
            .map(([userId, player]) => ({
                userId,
                name: player.name,
                kills: player.monsterKills || 0
            }))
            .sort((a, b) => b.kills - a.kills)
            .slice(0, 50);
    }

    getLingshiRanking() {
        return Object.entries(this.data.gameState)
            .map(([userId, player]) => ({
                userId,
                name: player.name,
                lingshi: player.lingshi || 0
            }))
            .sort((a, b) => b.lingshi - a.lingshi)
            .slice(0, 50);
    }

    getRealmRanking() {
        return Object.entries(this.data.gameState)
            .map(([userId, player]) => ({
                userId,
                name: player.name,
                realm: this.data.realms[player.realm],
                level: player.level
            }))
            .sort((a, b) => {
                if (a.realm !== b.realm) {
                    return this.data.realms.indexOf(b.realm) - this.data.realms.indexOf(a.realm);
                }
                return b.level - a.level;
            })
            .slice(0, 50);
    }

    getSectRanking() {
        return Object.entries(this.data.sects)
            .map(([sectName, sect]) => ({
                name: sectName,
                level: sect.level,
                members: sect.members.length,
                userId: sect.leader
            }))
            .sort((a, b) => b.level - a.level)
            .slice(0, 50);
    }

    getExplorationRanking() {
        return Object.entries(this.data.gameState)
            .map(([userId, player]) => ({
                userId,
                name: player.name,
                explorations: player.explorations || 0
            }))
            .sort((a, b) => b.explorations - a.explorations)
            .slice(0, 50);
    }

    getCombatPowerRanking() {
        return Object.entries(this.data.gameState)
            .map(([userId, player]) => ({
                userId,
                name: player.name,
                combatPower: this.utils.calculateCombatPower(player)
            }))
            .sort((a, b) => b.combatPower - a.combatPower)
            .slice(0, 50);
    }

    formatRanking(type, ranking) {
        let msg = '';
        ranking.forEach((item, index) => {
            const rank = index + 1;
            const medal = rank <= 3 ? ['🥇', '🥈', '🥉'][rank - 1] : `${rank}.`;
            const avatarUrl = `![图片 #20px #20px](https://q1.qlogo.cn/g?b=qq&s=0&nk=${item.userId})`;

            msg += `${avatarUrl}${medal} **${item.name}**`;

            switch (type) {
                case '妖怪击杀':
                    msg += ` - 击杀数: ${item.kills}`;
                    break;
                case '灵石':
                    msg += ` - 灵石: ${item.lingshi}`;
                    break;
                case '境界修为':
                    msg += ` - 境界: ${item.realm} (等级: ${item.level})`;
                    break;
                case '宗门':
                    msg += ` - 等级: ${item.level} (成员: ${item.members})`;
                    break;
                case '探索':
                    msg += ` - 探索次数: ${item.explorations}`;
                    break;
                case '战斗力':
                    msg += ` - 战斗力: ${item.combatPower}`;
                    break;
            }
            msg += '\n';
        });
        return msg;
    }
}
